package com.wugh.fast.security.core.web;


import com.alibaba.fastjson.JSON;
import com.wugh.fast.kernel.util.HttpUtils;
import com.wugh.fast.module.api.vo.ResponseVO;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 说明:
 *
 * @author wugh
 * @date 2018-09-14 16:22
 */
public class JsonLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint implements InitializingBean {

    /**
     * @param loginFormUrl URL where the login page can be found. Should either be
     *                     relative to the web-app context path (include a leading {@code /}) or an absolute
     *                     URL.
     */
    public JsonLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (HttpUtils.isAjaxRequest(request)) {
            Map<String, String> map = new HashMap<>();
            map.put("location", this.getLoginFormUrl());
            ResponseVO<Map<String, String>> ok = ResponseVO.ok(map);
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ok));
        } else {
            super.commence(request, response, authException);
        }
    }
}
